 insert into asm_camera_commercio_fat           
 select ar.cuf_id,
 sum(case when ar.voce_id in (205) then fatvoceot_pu else 0 end) SBIL,
  sum(case when (ar.ot_des like '%INDICIZZAT%' or ar.ot_des like '% PE %') and ar.voce_id in (234,225) then fatvoceot_pu else 
                    case when  (ar.ot_des like '%INDICIZZAT%' or ar.ot_des like '% PE %') and ar.voce_id = 311 and rif.voce_id in(333,337,343)
                                then  rif.SCR_PU else 0 end end) pv0,
  
  sum(case when (ar.ot_des like '%INDICIZZAT%' or ar.ot_des like '% PE %') and ar.voce_id in (207,226) then fatvoceot_pu else 0 end) pv1, 
  sum(case when (ar.ot_des like '%INDICIZZAT%' or ar.ot_des like '% PE %') and ar.voce_id in (208,227) then fatvoceot_pu else 0 end) pv2,
  sum(case when (ar.ot_des like '%INDICIZZAT%' or ar.ot_des like '% PE %') and ar.voce_id in (209,228) then fatvoceot_pu else 0 end) pv3,
 

 sum(case when ar.ot_des not like '%INDICIZZAT%' and  ar.ot_des not like '% PE %' and ar.voce_id in (234,342) then fatvoceot_pu else 
                    case when  (ar.ot_des not like '%INDICIZZAT%' and  ar.ot_des not like '% PE %') and ar.voce_id = 311 and rif.voce_id in(333,337,343)
                                then  rif.SCR_PU else 0 end end) pf0,
  sum(case when ar.ot_des not like '%INDICIZZAT%' and  ar.ot_des not like '% PE %' and ar.voce_id in (207,226) then fatvoceot_pu else 0 end) pf1, 
  sum(case when ar.ot_des not like '%INDICIZZAT%' and  ar.ot_des not like '% PE %' and ar.voce_id in (208,227) then fatvoceot_pu else 0 end) pf2,
  sum(case when ar.ot_des not like '%INDICIZZAT%' and  ar.ot_des not like '% PE %' and ar.voce_id in (209,228) then fatvoceot_pu else 0 end) pf3
 
 
 
  from v_scrittura_riferimenti rif,asm_camera_commercio_con cc,
  ( select fr3.* from v_fatturar fr3,

(select distinct fr1.cuf_id,fr1.tfat_id,voce_id,max(fr1.RFAT_ID) rfat_id
  from v_fatturar fr1,
  (select distinct fr.cuf_id,max(fr.tfat_id) tfat_id from v_fatturar fr,asm_camera_commercio_con cco
   where fr.az_id ='01'
   and    fr.cuf_id = cco.cuf_id
   
 
   group by fr.cuf_id) mfar
   where mfar.tfat_id = fr1.tfat_id
   and   mfar.cuf_id = fr1.cuf_id
   and fr1.ver_dtini >= to_date(^data inizio periodo ggmmaaaa ;A;Alfanumerico;1^^ ,'ddmmyyyy')
   and  fr1.ver_dtini <= to_date(^data fine periodo ggmmaaaa ;A;Alfanumerico;2^^ ,'ddmmyyyy')
   and   fr1.az_id ='01'

   group by fr1.cuf_id,fr1.tfat_id,voce_id) fr2
 where fr3.az_id ='01'
 and   fr3.cuf_id= fr2.cuf_id
 and   fr3.rfat_id = fr2.rfat_id
 and   fr3.tfat_id = fr2.tfat_id
 and   fr3.voce_id = fr2.voce_id) ar
   
 where 
         ar.az_id = '01'
        and ar.VOCE_ID in (205,207,208,209,225,226,227,228,234,311,342)
        
    
        and ar.rfat_id = rif.rfat_id(+)
        and rif.az_id(+) = '01'
        and rif.rvv_voce_id(+) = ar.voce_id
      
        
        and cc.cuf_id = ar.cuf_id
 group by ar.cuf_id
